/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.server.modules.sys.web.schedule;

import com.server.common.persistence.Page;
import com.server.common.utils.StringUtils;
import com.server.common.web.BaseController;
import com.server.modules.sys.common.StaticDefine;
import com.server.modules.sys.entity.User;
import com.server.modules.sys.entity.schedule.Schedule;
import com.server.modules.sys.entity.schedule.ScheduleUser;
import com.server.modules.sys.service.schedule.ScheduleService;
import com.server.modules.sys.service.schedule.ScheduleUserService;
import com.server.modules.sys.utils.UserUtils;
import com.server.modules.sys.vo.web.ScheduleViewAO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 日程Controller
 * @author 丁光彪
 * @version 2016-12-23
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/schedule/schedule")
public class ScheduleController extends BaseController {

	@Autowired
	private ScheduleService scheduleService;


	@Autowired
	private ScheduleUserService scheduleUserService;
	
	@ModelAttribute
	public Schedule get(@RequestParam(required=false) String id) {
		Schedule entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = scheduleService.get(id);
		}
		if (entity == null){
			entity = new Schedule();
		}else{
			ScheduleUser su=new ScheduleUser();
			su.setScheduleId(entity.getId());
            List<ScheduleUser> list = scheduleUserService.findList(su);
            if(!CollectionUtils.isEmpty(list)){
                if(list.size()==1){
                    entity.setScheduleUser(list.get(0));
                }else {
                    for (ScheduleUser scheduleUser : list) {
                        if(scheduleUser.getIsCreater()==null||!scheduleUser.getIsCreater()){
                            entity.setScheduleUser(scheduleUser);
                            break;
                        }
                    }
                }

            }
            
        }
		return entity;
	}
	
	@RequiresPermissions("sys:schedule:schedule:view")
	@RequestMapping(value = {"list", ""})
	public String list(Schedule schedule, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Schedule> page = scheduleService.findPage(new Page<Schedule>(request, response), schedule); 
		model.addAttribute("page", page);
		model.addAttribute("schedule", schedule);
		return "modules/sys/schedule/scheduleList";
	}

	@RequiresPermissions("sys:schedule:schedule:edit")
	@RequestMapping(value = "form")
	public String form(Schedule schedule, Model model) {
		model.addAttribute("schedule", schedule);
		return "modules/sys/schedule/scheduleForm";
	}

	/*@RequiresPermissions("sys:schedule:schedule:edit")*/
	@RequestMapping(value = "dialog/new")
	public String dialogNew(Schedule schedule, Model model) {

		return "modules/sys/schedule/dialog/new";
	}
	@RequestMapping(value = "dialog/edit")
	public String dialogEdit(Schedule schedule, Model model) {
		Long intervalNum=schedule.getIntervalNum();
		if(schedule.getIsRepeat()&&intervalNum!=null){
			switch(schedule.getRepeatType()){
				case StaticDefine.DIC_REPEAT_TYPE.DAY:
					intervalNum=schedule.getIntervalNum()/Long.parseLong("86400");
					break;
				case StaticDefine.DIC_REPEAT_TYPE.WEEK:
					intervalNum=schedule.getIntervalNum()/(Long.parseLong("86400")*7);
					break;
			}
			schedule.setIntervalNumStr(Long.toString(intervalNum));
		}
		model.addAttribute("obj",schedule);
		return "modules/sys/schedule/dialog/edit";
	}

	@RequiresPermissions("sys:schedule:schedule:edit")
	@RequestMapping(value = "saveNew")
	@ResponseBody
	public Object saveNew(Schedule schedule, Model model,String scheduleUsersStr) {
		Map<String,Object> ret=new HashMap<>();
		if(StringUtils.isBlank(scheduleUsersStr)){
			ret.put("msg","请选择事项参与人");
			return ret;
		}
		if(StringUtils.isBlank(schedule.getStartTimeStr())||StringUtils.isBlank(schedule.getEndTimeStr())){
			ret.put("msg","填写事项开始时间和结束时间");
			return ret;
		}
		if( schedule.getIsAllDay()){
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			try {
				Date startTime=format.parse(schedule.getStartDateStr());
				schedule.setStartTime(startTime);
			} catch (ParseException e) {
				ret.put("msg","日程开始时间格式错误");
				return ret;
			}
			try {
				Date endTime=format.parse(schedule.getEndDateStr());
				schedule.setEndTime(endTime);
			} catch (ParseException e) {
				e.printStackTrace();
				ret.put("msg","日程结束时间格式错误");
				return ret;
			}
		}else{
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			try {
				Date startTime=format.parse(schedule.getStartDateStr()+" "+schedule.getStartTimeStr());
				schedule.setStartTime(startTime);
			} catch (ParseException e) {
				ret.put("msg","日程开始时间格式错误");
				return ret;
			}
			try {
				Date endTime=format.parse(schedule.getEndDateStr()+" "+schedule.getEndTimeStr());
				schedule.setEndTime(endTime);
			} catch (ParseException e) {
				ret.put("msg","日程结束时间格式错误");
				return ret;
			}
		}
		//重复截止
		if(schedule.getIsRepeat()&&!schedule.getIsRepeatForever() ){
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			try {
				Date repeatEndTime=format.parse(schedule.getRepeatEndTimeStr());
				schedule.setRepeatEndTime(repeatEndTime);
			} catch (ParseException e) {
					ret.put("msg","日程重复截止时间格式错误");
				return ret;
			}
		}
		if(schedule.getType().equals("other")||schedule.getType().equals("0")){
			schedule.setType(StaticDefine.DIC_SCHEDULE_TYPE.OTHER);
		}
		if(schedule.getType().equals("matter")||schedule.getType().equals("1")){
			schedule.setType(StaticDefine.DIC_SCHEDULE_TYPE.MATTER);
		}
		scheduleService.saveNew(schedule,scheduleUsersStr);
		ret.put("msg","保存成功");
		ret.put("isSuccess",true);
		return ret;
	}
    @RequiresPermissions("sys:schedule:schedule:edit")
    @RequestMapping(value = "saveEdit")
	@ResponseBody
    public Object saveEdit(Schedule schedule, String scheduleUsersStr) {
        Map<String,Object> ret=new HashMap<>();
        if(StringUtils.isBlank(scheduleUsersStr)){
            ret.put("msg","请选择事项参与人");
            return ret;
        }
        if(StringUtils.isBlank(schedule.getStartTimeStr())||StringUtils.isBlank(schedule.getEndTimeStr())){
            ret.put("msg","填写事项开始时间和结束时间");
            return ret;
        }
        if( schedule.getIsAllDay()){
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date startTime=format.parse(schedule.getStartDateStr());
                schedule.setStartTime(startTime);
            } catch (ParseException e) {
                ret.put("msg","日程开始时间格式错误");
                return ret;
            }
            try {
                Date endTime=format.parse(schedule.getEndDateStr());
                schedule.setEndTime(endTime);
            } catch (ParseException e) {
                e.printStackTrace();
                ret.put("msg","日程结束时间格式错误");
                return ret;
            }
        }else{
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            try {
                Date startTime=format.parse(schedule.getStartDateStr()+" "+schedule.getStartTimeStr());
                schedule.setStartTime(startTime);
            } catch (ParseException e) {
                ret.put("msg","日程开始时间格式错误");
                return ret;
            }
            try {
                Date endTime=format.parse(schedule.getEndDateStr()+" "+schedule.getEndTimeStr());
                schedule.setEndTime(endTime);
            } catch (ParseException e) {
                ret.put("msg","日程结束时间格式错误");
                return ret;
            }
        }
        //重复截止
        if(schedule.getIsRepeat()&&!schedule.getIsRepeatForever() ){
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date repeatEndTime=format.parse(schedule.getRepeatEndTimeStr());
                schedule.setRepeatEndTime(repeatEndTime);
            } catch (ParseException e) {
                ret.put("msg","日程重复截止时间格式错误");
                return ret;
            }
        }
        if(schedule.getType().equals("other")||schedule.getType().equals("0")){
            schedule.setType(StaticDefine.DIC_SCHEDULE_TYPE.OTHER);
        }
        if(schedule.getType().equals("matter")||schedule.getType().equals("1")){
            schedule.setType(StaticDefine.DIC_SCHEDULE_TYPE.MATTER);
        }
        scheduleService.saveEdit(schedule,scheduleUsersStr);
        ret.put("msg","保存成功");
        ret.put("isSuccess",true);
        return ret;
    }
	/**
	 * 获取全部日程
	 * @return
	 */
	@RequestMapping(value = "getAllSchedule", method = { RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public Object getAllSchedule(String type,String start,String end) {
		Date startTime=new java.util.Date(new Long(start)*1000);
		Date endTime=new java.util.Date(new Long(end)*1000);
		if("-1".equals(type)){
			type=null;
		}
		User user = UserUtils.getUser();
		List<ScheduleViewAO> data=scheduleService.getScheduleViewList(user.getId(), startTime, endTime, type,"ALL");
		return data;
	}


	@RequiresPermissions("sys:schedule:schedule:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public boolean delete(Schedule schedule) {
		try {
			scheduleService.delete(schedule);
			return true;
		}catch (Exception e){
			e.printStackTrace();
			return false;
		}


	}

    @RequestMapping(value = "isCreateUser")
    @ResponseBody
    public Object isCreateUser(Schedule schedule) {
        User user = UserUtils.getUser();
        if(user!=null&&schedule!=null&&schedule.getCreateBy()!=null&&schedule.getCreateBy().getId().equals(user.getId())){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 查看日程详情
     * @param id 日程标识
     * @param start 日程开始时间-由于有些重复日程的日期是计算得到的所以需要前端传入
     * @param end 日程结束时间
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = "detail")
    public String detail(String id,String start,String end,HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();

        Schedule schedule=scheduleService.get(id);
        boolean isCreater=false;
        if(schedule!=null&&user!=null){
            schedule.setStartDateStr(start);
            schedule.setEndDateStr(end);
            String remarks=schedule.getRemarks();
            if(StringUtils.isNotBlank(remarks)){
                //将\n和\r\n替换为</br>
                remarks = remarks.replaceAll("\r\n", "<br/>");
                remarks = remarks.replaceAll("\n", "<br/>");
                schedule.setRemarks(remarks);
            }
			User createBy = schedule.getCreateBy();
			if(createBy!=null&&createBy.getId().equals(user.getId())){
				isCreater=true;
			}
			model.addAttribute("schedule", schedule);
        }
        model.addAttribute("isCreater", isCreater);
        return "modules/sys/schedule/dialog/details";
    }

}